#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils


def get_plugin_info():
    plugin_info = {
        "name": "centos_access_control_018 Check_the_permissions_of_files_uploaded_by_FTP_users",
        "plugin_id": "centos_access_control_018",
        "plugin_type": "Access Control",
        "info": "Restrict the properties of files uploads by FTP users.",
        "level": "C",
        "module": "Safety reinforcement",
        "author": "congshz",
        "keyword": "Safety reinforcement",
        "configable": "false"
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


def scan_target(ip, target, cmd, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    # 获取参数信息
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    # 检错，每次执行命令都会进行检错，并决定返回退出/继续执行
    if not result and len(output) != 0 and not str(output[0]).startswith('#'):
        if "YES" in str(output[0]) or "022" in str(output[0]):
            des = target+" is SAFE."
        else:
            error_count += 1
            des = target+" is DANGEROUS."
    elif not result and len(output) != 0 and str(output[0]).startswith('#'):
        des = target+" is DISABLED."
        error_count += 1
    elif not result and len(output) == 0:
        des = target+" is NOT EXIST."
        error_count += 1
    else:
        error_des = "CMD process ERROR. Please check banner file."
        logger.debug_error(cur_user, cur_module, cur_task+'_Scan', '', error_des)
        des_list.append(error_des)
        error_count += 1
        return des_list, error_count
    logger.debug_info(cur_user, cur_module, cur_task + '_scan_target', '', des)
    des_list.append(des)
    return des_list, error_count


# 扫描函数
def scan(ip, sys_user, sys_pwd, flag=0):
    des_list = []
    error_count = 0
    vsftpd = 0
    log_file = None
    # 检查是否安装ftp软件
    cmd = "rpm -qa | grep ftp"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    # 检错，每次执行命令都会进行检错，并决定返回退出/继续执行
    if not result and len(output) == 0:
        des_list.append("FTP not installed.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "FTP not installed.")
        des_list.append("Scan Complete.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Complete.")
        return des_list, error_count
    elif not result and len(output) != 0:
        for i, value in enumerate(output):
            if value.find("vsftpd") != -1:
                vsftpd = 1
            ftp = value.replace("\n", "")
            ftp = ftp + " found"
            des_list.append(ftp)
            logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', ftp)
    else:
        error_des = "CMD process ERROR. Error info: {}".format(result[0].replace("\n", ""))
        des_list.append(error_des)
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', error_des)
        error_count += 1
        return des_list, error_count
    if vsftpd == 0:
        des_list.append("vsftp not installed.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "vsftp not installed.")
        des_list.append("Scan Complete.")
        logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', "Scan Complete.")
        return des_list, error_count

    check_cmd = "ls /etc/vsftpd"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        log_file = "/etc/vsftpd/vsftpd.conf"
    else:
        log_file = "/etc/vsftpd.conf"

    cmd_write = "cat " + log_file + " | grep write_enable= | grep -v anon"
    des_write, error_write = scan_target(ip, "write_enable", cmd_write, sys_user, sys_pwd)

    cmd_ls = "cat " + log_file + " | grep ls_recurse_enable="
    des_ls, error_ls = scan_target(ip, "ls_recurse_enable", cmd_ls, sys_user, sys_pwd)

    cmd_local = "cat " + log_file + " | grep local_umask="
    des_local, error_local = scan_target(ip, "local_umask", cmd_local, sys_user, sys_pwd)

    cmd_anon = "cat " + log_file + " | grep anon_umask="
    des_anon, error_anon = scan_target(ip, "anon_umask", cmd_anon, sys_user, sys_pwd)

    des_list = des_write + des_ls + des_local + des_anon
    error_count = error_write + error_ls + error_local + error_anon
    logger.debug_info(cur_user, cur_module, cur_task+'_Scan', '', 'Scan Complete.')
    des_list.append("Scan Complete.")
    if error_count != 0:
        # 是否加固
        if flag == 1:
            reinforce_des, reinforce_err = reinforce(ip, sys_user, sys_pwd, log_file)
            des_list.extend(reinforce_des)
            if reinforce_err == 0:
                error_count = 0
    return des_list, error_count


def reinforce_modify(ip, target, safe_target, sys_user, sys_pwd, log_file):
    des_list = []
    error_count = 0
    # 查找文件中需要更改的行，不硬编码以适应其他情况
    grep_cmd = "cat " + log_file + " | grep " + target
    result, output = CBBCommonUtils.cbb_run_cmd(ip, grep_cmd, username=sys_user, passwd=sys_pwd)
    if not result and len(output) != 0:
        # 组装命令
        safe_cmd = "sed -i '/" + output[0].replace("\n", "") + "/c" + safe_target + "' \"" + log_file + "\""
    elif not result and len(output) == 0:
        safe_cmd = "echo '" + safe_target + "'>>" + log_file
    else:
        error_count += 1
        cat_error = "Get target ERROR.Error info: {}.".format(result[0].replace("\n", ""))
        logger.debug_error(cur_user, cur_module, cur_task + '_reinforce_modify', '', cat_error)
        des_list.append(cat_error)
        return des_list, error_count
    # 修改对应行的内容
    result, output = CBBCommonUtils.cbb_run_cmd(ip, safe_cmd, username=sys_user, passwd=sys_pwd)
    if result:
        error_count += 1
        cat_error = "Get target ERROR.Error info: {}.".format(result[0].replace("\n", ""))
        logger.debug_error(cur_user, cur_module, cur_task + '_reinforce_modify', '', cat_error)
        des_list.append(cat_error)
    return des_list, error_count


# 加固函数
def reinforce(ip, sys_user, sys_pwd, log_file):
    des_list = []
    error_count = 0
    # 备份文件，文件名中的FF为FTP_FILE缩写，为了针对功能点控制备份文件用，避免备份冲突
    cmd = "cp " + log_file + " " + log_file + ".FF.`date +%Y-%m-%d`"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        # 检查是否备份成功
        if log_file == "/etc/vsftpd.conf":
            check_cmd = "ls /etc | grep vsftpd.conf.FF.`date +%Y-%m-%d`"
        else:
            check_cmd = "ls /etc/vsftpd | grep vsftpd.conf.FF.`date +%Y-%m-%d`"
        check_result, check_output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
        if not check_result and len(check_output) != 0:
            backup_check_des = "Backup SUCCEED."
            logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', backup_check_des)
        else:
            error_count += 1
            backup_check_des = "Backup check FAILED."
            logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', backup_check_des)
            des_list.append(backup_check_des)
            return des_list, error_count
    else:
        error_count += 1
        backup_des = "Backup FAILED."
        logger.debug_error(cur_user, cur_module, cur_task+'_Reinforce', '', backup_des)
        des_list.append(backup_des)
        return des_list, error_count

    # 修改参数
    safe_write = "write_enable=YES"
    safe_ls = "ls_recurse_enable=YES"
    safe_local_umask = "local_umask=022"
    safe_anon_umask = "anon_umask=022"
    des_write, error_write = reinforce_modify(ip, "write_enable= | grep -v anon", safe_write, sys_user, sys_pwd, log_file)
    des_ls, error_ls = reinforce_modify(ip, "ls_recurse_enable=", safe_ls, sys_user, sys_pwd, log_file)
    des_local, error_local = reinforce_modify(ip, "local_umask=", safe_local_umask, sys_user, sys_pwd, log_file)
    des_anon, error_anon = reinforce_modify(ip, "anon_umask=", safe_anon_umask, sys_user, sys_pwd, log_file)
    des_list.extend(des_write)
    des_list.extend(des_ls)
    des_list.extend(des_local)
    des_list.extend(des_anon)
    error_modify = error_write + error_ls + error_local + error_anon
    error_count = error_count + error_modify

    if error_modify != 0:
        # 加固失败，回滚
        rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
        des_list.extend(rollback_des)
        return des_list, error_count

    # 检查是否加固成功
    des_scan, error_scan = scan(ip, sys_user, sys_pwd)
    if error_scan != 0:
        # 加固失败，回滚
        rollback_des, rollback_err = rollback(ip, sys_user, sys_pwd)
        des_list.extend(rollback_des)
        return des_list, error_count

    des_list.append("Reinforce Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Reinforce', '', "Reinforce Complete.")
    return des_list, error_count


# 回滚函数
def rollback(ip, sys_user, sys_pwd):
    des_list = []
    error_count = 0
    log_file = None

    check_cmd = "ls /etc/vsftpd"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, check_cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        log_file = "/etc/vsftpd/vsftpd.conf"
    else:
        log_file = "/etc/vsftpd.conf"
    # 查找备份文件，此处的查找支持多备份文件的查找（结果会按时间顺序排序），并默认回滚最新一次备份的内容，可以连续多次回滚
    if log_file == "/etc/vsftpd.conf":
        grep_cmd = "ls /etc/ | grep vsftpd.conf.FF.*"
    else:
        grep_cmd = "ls /etc/vsftpd/ | grep vsftpd.conf.FF.*"
    result, output = CBBCommonUtils.cbb_run_cmd(ip, grep_cmd, username=sys_user, passwd=sys_pwd)
    if not result and len(output) != 0:
        logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "Backup file FOUND.")
        target = output[len(output) - 1].replace("\n", "")
        if log_file == "/etc/vsftpd.conf":
            cmd = "/bin/cp -rf /etc/" + target + " /etc/vsftpd.conf"
        else:
            cmd = "/bin/cp -rf /etc/vsftpd/" + target + " /etc/vsftpd/vsftpd.conf"
    else:
        error_count = -1
        des_list.append("Backup file NOT FOUND.")
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', "Backup file not found.")
        return des_list, error_count
    # 回滚文件，
    result, output = CBBCommonUtils.cbb_run_cmd(ip, cmd, username=sys_user, passwd=sys_pwd)
    if not result:
        logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "Rollback SUCCEED.")
        if log_file == "/etc/vsftpd.conf":
            del_cmd = "rm -rf /etc/" + target
        else:
            del_cmd = "rm -rf /etc/vsftpd/" + target
        # 删除对应的备份文件
        result, output = CBBCommonUtils.cbb_run_cmd(ip, del_cmd, username=sys_user, passwd=sys_pwd)
        if not result:
            del_des = "Backup file deleted. Target is {}.".format(target)
            logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
        else:
            error_count += 1
            del_des = "Backup file delete FAILED."
            des_list.append(del_des)
            logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', del_des)
            return des_list, error_count
    else:
        error_count += 1
        des = "Rollback FAILED, please retry."
        logger.debug_error(cur_user, cur_module, cur_task+'_Rollback', '', des)
        des_list.append(des)
        return des_list, error_count
    des_list.append("Rollback Complete.")
    logger.debug_info(cur_user, cur_module, cur_task+'_Rollback', '', "Rollback Complete.")
    return des_list, error_count


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        des_list = []
        des_start = "centos_access_control_018 Start."
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', des_start)
        if comm == 1:
            des_scan, error_scan = scan(ip, sys_user, sys_pwd, flag=0)
            des_list.extend(des_scan)
            step_error = int(error_scan)
        elif comm == 2:
            des_reinforce, error_reinforce = scan(ip, sys_user, sys_pwd, flag=1)
            des_list.extend(des_reinforce)
            step_error = int(error_reinforce)
        elif comm == 3:
            des_rollback, error_rollback = rollback(ip, sys_user, sys_pwd)
            des_list.extend(des_rollback)
            step_error = int(error_rollback)
        else:
            return {"code": 3, "count": 0, "des": ['command must be 1/2/3']}
        des_end = "centos_access_control_018 Complete."
        logger.debug_info(cur_user, cur_module, cur_task+'_Check', '', des_end)
        if step_error == 0:
            code = 0
        elif step_error <= -1:
            code = 2
        else:
            code = 1
        return {"code": code, "count": step_error, "des": des_list}
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        logger.debug_error(cur_user, cur_module, cur_task+'_Check', '', des)
        return {"code": code, "count": 0, "des": des}

# check(ip="127.0.0.1", system_user="root", system_pwd="1qaz!QAZ", command=0, flag=0)
